# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2023/11/19
desc: 
sample: 
"""
# -*- coding: utf-8 -*-
import logging
import time

import gevent
from locust.runners import WorkerRunner, STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP

from EmailUtils import EmailUtils

"""
author:码同学 极光
date:2023/11/19
desc: 
sample: 
"""
import os
import random

from locust import HttpUser, constant, between, task, FastHttpUser, events

#class LoginTest(HttpUser): 普通进程
from utils import getExcelList, getExcelDict


is_quitting = False
#指标不满足自动停止
def sendEmail(title, msg):
    emailUtils = EmailUtils()
    # 发送一封邮件
    emailUtils.send(title=title, Context=msg, to_addrs="279313259@qq.com")


def checker(environment, **kw):
    global is_quitting
    while not environment.runner.state in [STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP]:
        print("checker-----",environment.runner.stats.total.fail_ratio,
              environment.stats.total.avg_response_time,environment.stats.total.get_response_time_percentile(0.95))
        time.sleep(1) #需要等待系统启动注册
        if environment.runner.stats.total.fail_ratio > 0.01:
            logging.error("Test failed due to failure ratio > 1%")
            is_quitting = True
        elif environment.stats.total.avg_response_time > 200:
            logging.error(f"Test failed due to average response time ratio > 200ms,quitting")
            is_quitting = True
        elif environment.stats.total.get_response_time_percentile(0.95) > 300:
            logging.error(f"Test failed due to 95th percentile response time > 300, quitting")
            is_quitting = True

        if is_quitting:
            error_msg={}
            error_msg['错误率']= environment.runner.stats.total.fail_ratio
            error_msg['平均响应时间'] = str(int(environment.stats.total.avg_response_time))+"ms"
            error_msg['top95'] = str(int(environment.stats.total.get_response_time_percentile(95)))+"ms"
            print(error_msg)
            sendEmail(title='登陆压测指标不满足需求', msg="当前指标："+ error_msg.__str__())
            environment.runner.quit()
            return

#主节点监控
@events.init.add_listener
def on_locust_init(environment, runner, **_kwargs):
    if not isinstance(environment.runner, WorkerRunner):
        gevent.spawn(checker, environment)


class LoginTest(FastHttpUser): #协程
    host = 'http://82.156.74.26:9088/pinter'  # 可选
    #wait_time = between(1, 3) #思考时间
    # 静态变量 只读取一次
    excel_list = getExcelDict('case.xlsx')

    @task
    def login(self):
        url = '/com/login'
        params = random.choice(self.excel_list)
        #随机
        data = {"userName": params.get('usr'), 'password': params.get('psw')}
        with self.client.post(url=url,data=data, catch_response=True) as response:
            try:
                json = response.json()
                if json.get('message') == 'success':
                    response.success()
                else:
                    response.failure(json)
            except Exception as e:
                response.failure(e)



if __name__ == '__main__':
    os.system('locust -f locustMoniter.py --web-port 8092  -u 300 -r 10 -t 1h30m20s')